package com.qingzhou.web.service.impl.convert;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.qingzhou.system.service.ISysDictDataService;
import com.qingzhou.web.repository.entity.ImgTestInfo;
import com.qingzhou.web.service.util.DictUtil;
import io.swagger.annotations.ApiModelProperty;
import org.noear.solon.Solon;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ImgChestTestInfoConverter implements Converter<List<ImgTestInfo>> {
    @Override
    public WriteCellData<?> convertToExcelData(List<ImgTestInfo> value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        if(CollUtil.isEmpty(value)){
            WriteCellData<Object> emptyData = new WriteCellData<>("");
            emptyData.setType(CellDataTypeEnum.STRING);
            return emptyData;
        }
        return new WriteCellData<>(ImgChestTestInfoConverter.getConvertString(value));
    }

    public static String getConvertString(List<ImgTestInfo> value){
        if(CollUtil.isEmpty(value)) return "";

        List<String> rows = new ArrayList<>();
        ISysDictDataService dictDataService = Solon.context().getBean(ISysDictDataService.class);
        Class clazz = ImgTestInfo.class;
        for(ImgTestInfo item : value){
            List<String> inner = new ArrayList<>();
            Field[] keys = ClassUtil.getDeclaredFields(clazz);
            for(Field field : keys){
                String fieldName = field.getName();
                ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
                DictParent dictParent = field.getAnnotation(DictParent.class);
                if (apiModelProperty != null && !apiModelProperty.value().isEmpty()) {
                    fieldName = apiModelProperty.value();  // 使用注解中的 value 属性作为字段名
                }
                Object fieldValueObj = ReflectUtil.getFieldValue(item,field);
                String fieldValueStr = Convert.toStr(fieldValueObj, "");
                if(dictParent!=null && StrUtil.isNotEmpty(fieldValueStr)){
                    inner.add(fieldName+"："+ DictUtil.getLabel(fieldValueStr, dictParent.value()));
                }else{
                    inner.add(fieldName+"："+ fieldValueStr);
                }
            }
            rows.add(CollUtil.join(inner,"，"));
        }
        return CollUtil.join(rows,"；");
    }
}
